/**
 * 
 */
package cz.geoserver.KMLpublisher.servlet;

import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cz.geoserver.KMLpublisher.db.SQLExecutor;
import cz.geoserver.KMLpublisher.util.ServletUtil;

/**
 * Class creates new Geoserver OWS plugin on link /geoserver/ows?
 * Mandatory parameters with values:
 * request=publishKML
 * service=KMLpublisher
 * version=1.0.0
 * Mandatory parameters in combination:
 * 1. query
 * 2. sqlId & bbox
 * 3. query & bbox
 * 4. data_table & clustered_att & query
 * 5. data_table & clustered_att & query & bbox
 * @author mkepka
 */
public class DynamicKMLOws {

    private static String[] parBBOX = {"BBOX", "bbox", "Bbox"};
    private static String[] parQuery = {"QUERY", "query", "Query"};
    private static String[] parSqlId = {"SQLID","sqlId", "SQL_ID", "sql_id", "SqlId"};
    private ServletUtil sUtil;
    private static String propPath = "cz/geoserver/KMLpublisher/servlet/database.properties";

    /**
     * Constructor creates instance of OWS plugin and 
     * loads database connection properties from file in jar
     */
    public DynamicKMLOws(){
        try {
            //setting connection to DB
            URL urlProp = getClass().getClassLoader().getResource(propPath);
            Properties prop = new Properties();
            prop.load(urlProp.openStream());
            SQLExecutor.setProperties(prop);
        }catch (IOException e) {
            e.printStackTrace();
        }
        sUtil = new ServletUtil(false);
    }

    /**
     * Method processes incoming request, try to find any combination of mandatory parameters 
     * and if there is some useful combination, calls other utility classes that creates response to client
     * @param req - HttpServletRequest with parameters from client
     * @param resp - HttpServletResponse where to send response to client
     * @throws ServletException - Throws SQLException if an exception occurs while processing SQL queries
     * @throws IOException - Throws IOException if an exception occurs while loading file or sending response to client
     */
    public void publishKML(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Trying to find possible parameters in GET request
        Map paramMap = req.getParameterMap();
        String queryPar = sUtil.findParameterName(parQuery, paramMap);
        String bboxPar = sUtil.findParameterName(parBBOX, paramMap);
        String sesIdPar = sUtil.findParameterName(parSqlId, paramMap);
        
        try{
            // if there is any combination of query parameter or both sessionId and bbox parameter in request
            if(!queryPar.isEmpty() || (!sesIdPar.isEmpty() && !bboxPar.isEmpty())){
                sUtil.processRequest(req, resp);
            }
            // if there is not any known parameter in request
            else{
                resp.setContentType("text/html");
                resp.setStatus(400);
                ServletOutputStream out = resp.getOutputStream();
                out.println("Request does not contain required combination of parameters!");
            }
         } catch(SQLException e){
             resp.setContentType("text/html");
             resp.setStatus(400);
             ServletOutputStream out = resp.getOutputStream();
             out.println(e.getMessage());
         }
    }
}